package com.heima.search.service.impl;

import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.HistorySearchDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.search.model.pojos.ApUserSearch;
import com.heima.search.service.ApUserSearchService;
import com.heima.utils.thread.AppUserThreadLocal;
import com.heima.utils.thread.WmUserThreadLocal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.scheduling.annotation.Async;

import java.util.Date;
import java.util.List;

/**
 * @author shiminghui
 * @date 2024/12/12 17:09
 * @description: TODO
 */
public class ApUserSearchServiceImpl implements ApUserSearchService {
    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 保存用户搜索记录
     *
     * @param keyword
     * @param userId
     */
    @Override
    @Async // 异步执行
    public void insert(String keyword, Integer userId) {

        // 查询有没有
        List<ApUserSearch> apUserSearches =
                mongoTemplate.find(Query.query(Criteria.where("userId").is(userId).and("keyword").is(keyword)), ApUserSearch.class, "ap_user_search");
        //存在
        if (apUserSearches != null && apUserSearches.size() != 0) {
            // 将其的创建时间设置为现在
            apUserSearches.get(0).setCreatedTime(new Date());
            mongoTemplate.save(apUserSearches.get(0), "ap_user_search");
            return;
        }

        // 不存在
        // 判断搜索记录是否超过10条，超过就删除最早的一条记录
        long count = mongoTemplate.count(Query.query(Criteria.where("userId").is(userId)), ApUserSearch.class, "ap_user_search");
        if (count >= 10) {
            // 其实不需要删除,只需要将最后的那一个赋值为新的
            ApUserSearch apUserSearch = mongoTemplate.findOne(Query.query(Criteria.where("userId").is(userId).and("createdTime").lt(new Date())).with(Sort.by(Sort.Direction.DESC, "createdTime")), ApUserSearch.class, "ap_user_search");
            apUserSearch.setCreatedTime(new Date());
            apUserSearch.setKeyword(keyword);
//            mongoTemplate.save(apUserSearch, "ap_user_search");
            mongoTemplate.findAndReplace(Query.query(Criteria.where("id").is(apUserSearch.getId())), apUserSearch);
        } else {
            ApUserSearch apUserSearch = new ApUserSearch();
            apUserSearch.setUserId(userId);
            apUserSearch.setKeyword(keyword);
            apUserSearch.setCreatedTime(new Date());
            mongoTemplate.save(apUserSearch, "ap_user_search");
        }

    }

    /**
     * app端用户搜索记录
     *
     * @return
     */
    @Override
    public ResponseResult findUserSearch() {
        // 获取用户id
        ApUser user = AppUserThreadLocal.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        List<ApUserSearch> apUserSearches = mongoTemplate.find(Query.query(Criteria.where("userId").is(user.getId())).with(Sort.by(Sort.Direction.DESC, "createdTime")), ApUserSearch.class, "ap_user_search");
        if (apUserSearches == null) {
            return ResponseResult.errorResult(500, "查询失败");
        }
        return ResponseResult.okResult(apUserSearches);
    }

    /**
     * 删除历史记录
     *
     * @param historySearchDto
     * @return
     */
    @Override
    public ResponseResult delUserSearch(HistorySearchDto historySearchDto) {
        // 参数校验
        if (historySearchDto == null || historySearchDto.getId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 检测是否登录
        ApUser user = AppUserThreadLocal.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        // 删除
        mongoTemplate.findAndRemove(Query.query(Criteria.where("id").is(historySearchDto.getId()).and("userId").is(user.getId())), ApUserSearch.class, "ap_user_search");
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
